/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.rockville.filesystem;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.log4j.Logger;

/**
 *
 * @author Usman
 */
public class RunTime {

    private static final Logger log=Logger.getLogger(RunTime.class);
    // Used to identify user's platform.
    private static final String WIN_ID = "Windows";
    private static final String LINUX_ID = "Linux";
    
    // Error code for the last command 
    private static int exitVal = 0;
    
    /**
     * String[] cmd = {"/bin/bash", "-c", "ls -t1 *.XML | head 1";
     * @param command
     * @return
     */
    private static String executeOnRunTime_Linux(String[] command) {
        
        String retValue = "";
        String temp = "";
        
        log.debug("Linux Runtime Called.");
        log.debug("Executing Command: "+ com.rockville.util.StringUtil.Implode(command, " "));

        try {
            Runtime rt = Runtime.getRuntime();
            
            Process pr = rt.exec( command );
            
            BufferedReader br_input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
            
            while ((temp = br_input.readLine()) != null) {
                retValue = retValue +"\n"+ temp;
            }
            
            exitVal = pr.waitFor();
            log.debug("Exited with error code " + exitVal);

        } catch (Exception e) {
            retValue = "";
            log.error("Error encountered: ", e);
        }
        
        return retValue;
        
    }
    
    /**
     * <pre>
     * String cmd = "cmd /c "+ "dir /od /b \"c:\\*index.xml\\"";
     * </pre>
     * @param strCommand
     * @return
     */
    private static String executeOnRunTime_Windows(String strCommand) {
        String strOutput = "";
        Runtime r = null;
        boolean returnIs = false;
        
        log.debug("Windows Runtime Called.");
        log.debug("Executing command: "+ strCommand);
        
        try {
            r = Runtime.getRuntime();
            Process pMove = r.exec(strCommand);
            //int processReturnValue = pMove.waitFor();
            InputStream is = pMove.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String strLine;
            while ((strLine = br.readLine()) != null) {
                strOutput = strOutput + "\n" + strLine;
            }
            
            pMove = null;
            //String success_failure = processReturnValue == 0 ? "Successfull" : "Failure";
            //log.debug("returnValue by Dos Command Process: "+processReturnValue+" "+success_failure);
            //strOutput=strOutput+"\n"+"returnValue by Dos Command Process: "+processReturnValue+" "+success_failure;
            r = null;
            returnIs = true;
        }
        catch(Exception ex) {
            strOutput = "";
            log.error("Error encountered: ", ex);
        }
        return strOutput;
    }
    
    /**
     * <pre>
     * Email the output of the command to the specified EmailID.
     * 
     * </pre>
     * @param command
     * @param emailAddress
     */
    private static void emailCommandOutput(String command, String emailAddress) {

        if(isWindowsPlatform()) {
            log.debug("Not available for Windows");
        }
        else if(isLinuxPlatform()) {
            String subject = "Email from RunTime";
            String pipeFile = command +" | ";
            String email = emailAddress;
            String cmdline = "cat " + pipeFile + " mail -s " + subject + " " + email;
            String[] cmd = {"/bin/bash", "-c", cmdline};
            
            executeOnRunTime_Linux(cmd);
        }
        
    }
    
    /**
     * <pre>
     * Executes a command on the "Console"/"Dos prompt" and returns the result.
     * </pre>
     * @param command
     * @return String
     */
    public static String executeCommand(String command) {
        if(isWindowsPlatform()) {
            String cmd = "cmd /c "+ command;
            return executeOnRunTime_Windows(cmd);
        }
        else {
            String[] cmd = {"/bin/bash", "-c", command};
            return executeOnRunTime_Linux(cmd);
        }
    }
    
    /**
     * <pre>
     * Detect if the user OS is a windows platform
     * </pre>
     * @return boolean
     */
    public static boolean isWindowsPlatform() {
        String os = System.getProperty("os.name");
        
        if ( os != null && os.startsWith(WIN_ID))
            return true;
        else
            return false;
    }
    
    /**
     * <pre>
     * Detect if the user OS is a Linux platform
     * </pre>
     * @return boolean
     */
    public static boolean isLinuxPlatform() {
        String os = System.getProperty("os.name");
        
        if ( os != null && os.startsWith(LINUX_ID))
            return true;
        else
            return false;
    }
}
